require 'erb'
require 'yaml'
require 'net/http'
require 'singleton'

class HttpClient
  include Singleton

  class << self
    def get(url, params = {})
      instance.get url, params
    end

    def post(url, params = {})
      instance.post url, params
    end

    def init(params = {})
      instance.init params
    end
  end

  def get(url, params = {})
    uri = URI.parse(url)
    uri.query = URI.encode_www_form(params)

    req = Net::HTTP::Get.new(uri)

    do_request uri, req
  end

  def post(url, params = {})
    uri = URI.parse(url)

    req = Net::HTTP::Post.new(uri)
    req.set_form_data(params)

    do_request uri, req
  end

  def init(options = {})
    @proxy_file = options['proxy_file'] if options['proxy_file'] && !options['proxy_file'].empty?
    @env = options['env'] if options['env'] && !options['env'].empty?

    @client = @config = nil
  end

  private

  def proxy_file
    @proxy_file ||= File.expand_path('../http_proxy.yml', __FILE__)
  end

  def env
    @env ||= 'development'.freeze
  end

  def config
    @config ||= YAML::load(ERB.new(IO.read(proxy_file)).result)[env]
  end

  def client
    @client ||= Net::HTTP::Proxy(config['host'], config['port'], config['username'], config['password'])
  end

  def do_request(uri, req)
    client.start(uri.host, uri.port, use_ssl: uri.scheme.eql?('https')) {|http| http.request(req)}
  end
end
